#define _CRT_SECURE_NO_WARNINGS  1
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>



typedef int datatype;

typedef struct QNode
{
	datatype data;
	struct QNode* next;
}QNode;

typedef struct Queue
{
	QNode* head;
	QNode* tail;
	int size;
}Queue;


int QueueEmpty(Queue* pq);
void QueueInit(Queue* pq)
{
	assert(pq);

	pq->head = pq->tail = NULL;
	pq->size = 0;
}

void QueuePush(Queue* pq, datatype x)
{
	assert(pq);
	QNode* new = (QNode*)malloc(sizeof(QNode));
	if (new == NULL)
	{
		perror("malloc fail\n");
		return;
	}
	new->data = x;
	new->next = NULL;

	if (pq->head == NULL)
	{
		assert(pq->tail == NULL);

		pq->head = new;
		pq->tail = new;
	}
	else
	{
		pq->tail->next = new;
		pq->tail = new;
	}

	pq->size++;


}
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->head != NULL);

	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QNode* next = pq->head->next;
		free(pq->head);
		pq->head = next;

	}

	pq->size--;

}
datatype QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->head->data;
}
datatype QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->tail->data;
}
int QueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

int QueueEmpty(Queue* pq)
{
	assert(pq);

	if (pq->size == 0)
	{
		return 1;
	}
	return 0;
}

void QueueDestroy(Queue* pq)
{
	assert(pq);

	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}

	pq->head = pq->tail = NULL;
	pq->size = 0;
}

typedef struct
{
	Queue q1;
	Queue q2;
} MyStack;

bool myStackEmpty(MyStack* obj)
{
	return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
}

MyStack* myStackCreate()
{
	MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
	QueueInit(&obj->q1);
	QueueInit(&obj->q2);

	return obj;
}

void myStackPush(MyStack* obj, int x)
{
	if (!QueueEmpty(&obj->q1))
	{
		QueuePush(&obj->q1, x);
	}
	else
	{
		QueuePush(&obj->q2, x);
	}
}

int myStackPop(MyStack* obj)
{
	Queue* kong = &obj->q1;
	Queue* nokong = &obj->q2;
	if (!QueueEmpty(&obj->q1))
	{
		kong = &obj->q2;
		nokong = &obj->q1;
	}

	while (QueueSize(nokong) > 1)
	{
		QueuePush(kong, QueueFront(nokong));
		QueuePop(nokong);
	}

	int top = QueueFront(nokong);
	QueuePop(nokong);

	return top;

}

int myStackTop(MyStack* obj)
{
	if (!QueueEmpty(&obj->q1))
	{
		return QueueBack(&obj->q1);
	}
	else
		return QueueBack(&obj->q2);
}



void myStackFree(MyStack* obj)
{
	QueueDestroy(&obj->q1);
	QueueDestroy(&obj->q2);
	free(obj);
}
